package com.qt;

import com.qt.entity.Author;
import com.qt.entity.Book;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

public class OptionalDemo01 {

    public static void main(String[] args) {

        test13();

//        Author author = getAuthor();
//        Optional<Author> optionalAuthor = Optional.ofNullable(author);
//        optionalAuthor.ifPresent(author1 -> System.out.println(author1.getName()));
//        Optional<Author> authorOptional = getAuthorOptional();
//        authorOptional.ifPresent(author -> System.out.println(author.getName()));

        //get  直接get不推荐
//        Author author = authorOptional.get();
//        Author author1 = authorOptional.orElseGet(() -> new Author());

//        try {
//            Author author2 = authorOptional.orElseThrow(() -> new RuntimeException("传入数据为空！"));
//        } catch (Throwable e) {
//            e.printStackTrace();
//        }

//        Author author = getAuthor();


        //getAuthorOptional().filter(author1 -> author1.getAge() > 18).ifPresent(author1 -> System.out.println(author1.getName()));

//        Optional<Author> optionalAuthor = getAuthorOptional().filter(author1 -> author1.getAge() > 18);
//        if(optionalAuthor.isPresent()){
//            System.out.println(optionalAuthor.get());
//        }

    }

    private static void test13() {

        Optional<Author> authorOptional = getAuthorOptional();
        Optional<List<Book>> books = authorOptional.map(author -> {
            Book book = new Book(1L, "凡人修仙传", "123", 24, "来自炸鸡店的小伙子");
            List<Book> books1 = new ArrayList<>();
            books1.add(book);
            author.setBooks(books1);
            return author.getBooks();
        });
        books.ifPresent(books1 -> System.out.println(books1));

    }

    private static Optional<Author> getAuthorOptional() {

        Author author = new Author(1L, "懵躲", 23, "狂狼一条该", null);
        return Optional.ofNullable(author);

    }

    private static Author getAuthor() {

        Author author = new Author(1L, "懵躲", 23, "狂狼一条该", null);
        return author;

    }


}
